import {musicUrl, playListDetail, songDetail} from "@/api/apis";
import axios from 'axios'

export default {
  namespaced: true,
  state: {
    id: '',
    list: [],
    song: '',
    music_urls: [],
    isPlay: false,
    currentTime: 0
  },
  mutations: {
    // 正在播放音乐的id
    SET_ID: (state, data) => {
      state.id = data
    },
    // 播放列表
    SET_PLAYER_LIST: (state, data) => {
      state.list = data
    },
    // 设置当前播放歌曲
    SET_CURRENT_SONG: (state, data) => {
      state.song = data
    },
    // 设置歌曲播放地址
    SET_MUSIC_URLS: (state, data) => {
      state.music_urls = data
    },
    // 播放状态
    SET_IS_PLAY: (state, data) => {
      console.log(data)
      state.isPlay = data
    },
    // 时间
    SET_CURRENT_TIME: (state, data) => {
      state.currentTime = data
    }
  },
  actions: {
    playMusic({commit, state, dispatch}, id) {
      if (id !== state.id) {
        dispatch('playMusicId', id)
        commit('SET_IS_PLAY', false);
        commit('SET_CURRENT_TIME', 0);
        songDetail({ids: id}).then(res => {
          commit('SET_CURRENT_SONG', res.songs[0])
        });
        dispatch('playMusicUrl', id)
      }
    },
    playMusicUrl({commit, state, dispatch}, id) {
      musicUrl({id}).then(res => {
        commit('SET_MUSIC_URLS', res.data)
        commit('SET_IS_PLAY', true)
      })
    },
    // 全部播放
    playPlaylist({commit, state, dispatch}, id) {
      playListDetail({id}).then(res => {
        commit('SET_PLAYER_LIST', res.playlist.tracks);
        dispatch('playMusic', res.playlist.tracks[0].id)
      })
    },
    playMusicId({commit, state}, id) {
      commit('SET_ID', id);
    },
    // 下载歌曲
    downloadMusic({commit, state, dispatch}, id) {
      musicUrl({id}).then(res => {
        console.log(res.data)

        let fileName = '起风了.mp3' // 文件名设置: 起风了
        let downURL = res.data[0].url
        console.log(downURL)
        axios({
          method: 'get',
          url: downURL,
          responseType: 'blob',
          headers: {'content-type': 'audio/mpeg'}
          // headers: {'content-length': '4066786', 'content-type': 'audio/mpeg'}
        }).then((res) => {
          // eslint-disable-next-line no-unused-vars
          let blobType = 'application/force-download' // 设置blob请求头
          // eslint-disable-next-line no-unused-vars
          let blob = new Blob([res.data], {type: res.data.type}) // 创建blob 设置blob文件类型 data 设置为后端返回的文件(例如mp3,jpeg) type:这里设置后端返回的类型 为 mp3
          let downa = document.createElement('a') // 创建A标签
          // eslint-disable-next-line no-unused-vars
          let href = window.URL.createObjectURL(blob) // 创建下载的链接
          downa.href = href // 下载地址
          downa.download = fileName // 下载文件名
          document.body.appendChild(downa)
          downa.click() // 模拟点击A标签
          document.body.removeChild(downa) // 下载完成移除元素
          window.URL.revokeObjectURL(href) // 释放blob对象
        }).catch(function (error) {
          console.log(error)
        })
      })
    }
  }
}
